package com.pn.taikao.service.impl;

import com.pn.taikao.common.ResultCode;
import com.pn.taikao.entity.Class;
import com.pn.taikao.exception.BusinessException;
import com.pn.taikao.mapper.ClassMapper;
import com.pn.taikao.service.ClassService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class ClassServiceImpl implements ClassService {

    private final ClassMapper classMapper;

    public ClassServiceImpl(ClassMapper classMapper) {
        this.classMapper = classMapper;
    }

    @Override
    public Long createClass(Class clazz) {
        // 检查班级名称是否已存在
        if (StringUtils.hasText(clazz.getName())) {
            Class exist = classMapper.selectByName(clazz.getName());
            if (exist != null) {
                throw new BusinessException(ResultCode.PARAM_ERROR, "班级名称已存在");
            }
        }
        
        if (clazz.getCreateTime() == null) {
            clazz.setCreateTime(LocalDateTime.now());
        }
        if (clazz.getUpdateTime() == null) {
            clazz.setUpdateTime(LocalDateTime.now());
        }
        classMapper.insert(clazz);
        return clazz.getId();
    }

    @Override
    public void updateClass(Class clazz) {
        // 检查班级名称是否已存在（排除自己）
        if (StringUtils.hasText(clazz.getName())) {
            Class exist = classMapper.selectByName(clazz.getName());
            if (exist != null && !exist.getId().equals(clazz.getId())) {
                throw new BusinessException(ResultCode.PARAM_ERROR, "班级名称已存在");
            }
        }
        clazz.setUpdateTime(LocalDateTime.now());
        classMapper.update(clazz);
    }

    @Override
    public void deleteClass(Long id) {
        classMapper.deleteById(id);
    }

    @Override
    public Class getById(Long id) {
        return classMapper.selectById(id);
    }

    @Override
    public List<Class> getByMajorId(Long majorId) {
        return classMapper.selectByMajorId(majorId);
    }

    @Override
    public List<Class> list(String name, Long majorId, int page, int size) {
        int offset = Math.max(page, 1);
        offset = (offset - 1) * Math.max(size, 1);
        return classMapper.selectPage(name, majorId, offset, size);
    }

    @Override
    public long count(String name, Long majorId) {
        return classMapper.count(name, majorId);
    }
}